#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"
#include "fcntl.h"
#include "semaphore.h"
#define STACK_SIZE 512

struct semaphore* mySem;
int semID;
void* threadRun()
{
  int processId = thread_getProcId();
  int threadId = thread_getid();

  int i,j;
  for(j=0;j<1;j++){
    sem_down(mySem);
    for (i = 0;i<3;i++){
      printf(1,"Process %d Thread %d is running\n",processId,threadId);
    }
    sem_up(mySem);
    sleep(1);
  }
  thread_exit(0);
 return 0;
}

void
threadTest(int num)
{
  int i = 0;
  void* threadStack;
  int threadsList[num];
  for (i = 0;i < num;i++)
  {
   threadStack = malloc(STACK_SIZE);
   threadsList[i] = thread_create(&threadRun,threadStack,STACK_SIZE);
  }

  for(i = 0;i < num;i++)
  {
    thread_join(threadsList[i],0);
  }
}



int
main(int argc, char *argv[])
{
  
  if(argc < 2){
    printf(1,"Invalid argument");
    exit();
  }

  mySem = semaphore_create(1);
  sem_up(mySem);
  threadTest(atoi(argv[1]));

  exit();
}  
